package com.zbkj.crmeb.store.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.CommonPage;
import com.common.PageParamRequest;
import com.constants.Constants;
import com.crmeb.core.exception.CrmebException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.utils.DateUtil;
import com.utils.vo.dateLimitUtilVo;
import com.zbkj.crmeb.chant.model.CategoryMatch;
import com.zbkj.crmeb.chant.service.ICategoryMatchService;
import com.zbkj.crmeb.enums.OrderStatusEnum;
import com.zbkj.crmeb.enums.logistics.DeliveryChannelEnum;
import com.zbkj.crmeb.store.dao.PurchaseGoodsDao;
import com.zbkj.crmeb.store.model.*;
import com.zbkj.crmeb.store.request.StoreOrderSearchRequest;
import com.zbkj.crmeb.store.response.*;
import com.zbkj.crmeb.store.service.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class PurchaseGoodsServiceImpl extends ServiceImpl<PurchaseGoodsDao, PurchaseGoods> implements PurchaseGoodsService {

    @Autowired
    private StoreBrandService storeBrandService;
    @Autowired
    private StoreOrderInfoService storeOrderInfoService;
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private ICategoryMatchService categoryMatchService;
    @Autowired
    private OrderInfoDeliveryService orderInfoDeliveryService;
    @Autowired
    private SupplierService supplierService;

    @Override
    public SupplierOrderResponse purchaseOrderList(StoreOrderSearchRequest request, PageParamRequest pageParamRequest) {
        if(StringUtils.isNotBlank(request.getSuppliersId())){
            Supplier supplier = supplierService.getById(request.getSuppliersId());
            if(supplier == null){
                throw new CrmebException("该供应商不存在");
            }
            request.setIsEurope(supplier.getIsEurope());
        }
        SupplierOrderResponse response = new SupplierOrderResponse();
        //状态数量
        response.setStatus(
                new StoreOrderCountItemResponse(
                        getCount(request, Constants.ORDER_STATUS_ALL), //全部
                        null, //未支付
                        getCount(request, Constants.ORDER_STATUS_NOT_SHIPPED), //未发货
                        getCount(request, Constants.ORDER_STATUS_SPIKE), //待收货
                        getCount(request, Constants.ORDER_STATUS_COMPLETE),//交易完成
                        getCount(request, Constants.ORDER_STATUS_REFUNDING),//退款中
                        getCount(request, Constants.ORDER_STATUS_REFUNDED),//退货退款
                        null,//补偿性退款
                        getCount(request, Constants.ORDER_STATUS_CONFIRM),//待确认
                        getCount(request, Constants.ORDER_STATUS_CANCEL)//已取消
                )
        );
        //列表数据
        List<SupplierOrderItemResponse> storeOrderItemResponseArrayList = new ArrayList<>();
        StoreOrderSearchRequest searchRequest = new StoreOrderSearchRequest();
        BeanUtils.copyProperties(request, searchRequest);
        QueryWrapper<PurchaseGoods> lambdaQueryWrapper = getStoreOrderListRequest(searchRequest);
        Page<Object> page = PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        //查询子订单
        List<PurchaseGoods> purchaseGoodsList = this.list(lambdaQueryWrapper);
        if (CollectionUtils.isNotEmpty(purchaseGoodsList)) {
            storeOrderItemResponseArrayList = formatOrder(purchaseGoodsList);
        }
        BigDecimal amount = BigDecimal.ZERO;
        BigDecimal amountEur = BigDecimal.ZERO;
        lambdaQueryWrapper.select("sum(ceil(goods_price/exchange_rate*100)/100) goods_ot_price, sum(goods_price) goods_price");
        PurchaseGoods goodsServiceOne = this.getOne(lambdaQueryWrapper);
        if (goodsServiceOne != null) {
            amount = goodsServiceOne.getGoodsPrice().setScale(2, RoundingMode.DOWN);
            amountEur = goodsServiceOne.getGoodsOtPrice().setScale(2, RoundingMode.DOWN);
        }
        CommonPage<SupplierOrderItemResponse> storeOrderItemResponseCommonPage = CommonPage.restPage(CommonPage.copyPageInfo(page, storeOrderItemResponseArrayList));
        response.setList(storeOrderItemResponseCommonPage);
        //头部数据
        pageParamRequest.setLimit(1);
        response.setTop(new StoreOrderTopItemResponse(getCount(request, request.getStatus()), amount, amountEur, null, null));
        return response;
    }

    private List<SupplierOrderItemResponse> formatOrder(List<PurchaseGoods> purchaseGoodsList) {
        List<Integer> orderInfoIdList = purchaseGoodsList.stream().map(PurchaseGoods::getStoreOrderInfoId).distinct().collect(Collectors.toList());
        List<StoreOrderInfo> storeOrderInfoList = storeOrderInfoService.list(Wrappers.<StoreOrderInfo>lambdaQuery().in(StoreOrderInfo::getId, orderInfoIdList));
        Map<Integer, StoreOrderInfo> orderInfoMap = storeOrderInfoList.stream().collect(Collectors.toMap(StoreOrderInfo::getId, e -> e));
        List<Integer> orderIdList = storeOrderInfoList.stream().map(StoreOrderInfo::getOrderId).distinct().collect(Collectors.toList());
        List<StoreOrder> storeOrderList = storeOrderService.list(Wrappers.<StoreOrder>lambdaQuery().in(StoreOrder::getId, orderIdList));
        Map<Integer, StoreOrder> orderMap = storeOrderList.stream().collect(Collectors.toMap(StoreOrder::getId, e -> e));
        List<Integer> cateIdList = purchaseGoodsList.stream().map(PurchaseGoods::getGoodsCateId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
        cateIdList.add(0);
        List<CategoryMatch> categoryMatchList = categoryMatchService.list(Wrappers.<CategoryMatch>lambdaQuery().in(CategoryMatch::getId, cateIdList).eq(CategoryMatch::getType,1));
        Map<Integer, String> cateMap = categoryMatchList.stream().collect(Collectors.toMap(CategoryMatch::getId, CategoryMatch::getName));
        List<SupplierOrderItemResponse> responseList  = new ArrayList<>();
        for (PurchaseGoods good : purchaseGoodsList) {
            SupplierOrderItemResponse response = new SupplierOrderItemResponse();
            BeanUtils.copyProperties(good,response);
            if(good.getRefundStatus() == 1){
                response.setStatus(OrderStatusEnum.APPLY_REFUND.getCode());
            }
            response.setGoodsPrice(good.getGoodsPrice());
            //商品货号 分类
            StoreOrderInfo storeOrderInfo = orderInfoMap.get(good.getStoreOrderInfoId());
            StoreCartResponse storeCartResponse = JSON.parseObject(storeOrderInfo.getInfo(), StoreCartResponse.class);
            response.setKeyword(storeCartResponse.getProductInfo().getKeyword());
            //收货信息
            StoreOrder storeOrder = orderMap.get(storeOrderInfo.getOrderId());
            response.setAddress(storeOrderInfo.getDeliveryAddress());
            response.setUserName(storeOrder.getRealName());
            response.setUserPhone(storeOrder.getUserPhone());
            response.setIdCard(storeOrder.getIdCard());
            //物流信息
            response.setTempId(good.getGoodsTempId());
            List<OrderInfoDelivery> deliveryList = orderInfoDeliveryService.list(Wrappers.<OrderInfoDelivery>lambdaQuery().eq(OrderInfoDelivery::getChannel, DeliveryChannelEnum.SUPPLIER.getCode())
                    .eq(OrderInfoDelivery::getOrderInfoId, good.getStoreOrderInfoId()));
            response.setDeliveryList(deliveryList);
            response.setCateName(cateMap.get(good.getGoodsCateId()));
            responseList.add(response);
        }
        return responseList;
    }

    private QueryWrapper<PurchaseGoods> getStoreOrderListRequest(StoreOrderSearchRequest request) {
        QueryWrapper<PurchaseGoods> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(PurchaseGoods::getPushStatus,1)
                .orderByDesc(PurchaseGoods::getCreateTime);
        if(request.getIsEurope() != null){
            queryWrapper.lambda().eq(PurchaseGoods::getChannelType,request.getIsEurope());
        }
        if(StringUtils.isNotBlank(request.getDateLimit())) {
            dateLimitUtilVo dateLimitUtilVo = DateUtil.getDateLimit(request.getDateLimit());
            request.setStartTime(dateLimitUtilVo.getStartTime());
            request.setEndTime(dateLimitUtilVo.getEndTime());
        }
        if(StringUtils.isNotBlank(request.getStartTime())){
            queryWrapper.lambda().ge(PurchaseGoods::getCreateTime,request.getStartTime());
        }
        if(StringUtils.isNotBlank(request.getEndTime())){
            queryWrapper.lambda().le(PurchaseGoods::getCreateTime,request.getEndTime());
        }
        if(StringUtils.isNotBlank(request.getOrderId())){
            queryWrapper.lambda().eq(PurchaseGoods::getChannelOrderSn,request.getOrderId());
        }
        if(StringUtils.isNotBlank(request.getBrandIdList())){
            List<String> brandIdList = Arrays.asList(request.getBrandIdList().split(","));
            List<StoreBrand> storeBrandList = storeBrandService.list(Wrappers.<StoreBrand>lambdaQuery().in(StoreBrand::getId, brandIdList).eq(StoreBrand::getType, 1));
            List<String> brandList = storeBrandList.stream().map(StoreBrand::getEnName).distinct().collect(Collectors.toList());
            if(CollectionUtils.isNotEmpty(brandList)){
                queryWrapper.lambda().in(PurchaseGoods::getGoodsBrand,brandList);
            }
        }
        if(StringUtils.isNotBlank(request.getCateIdList())){
            List<String> cateIdList = Arrays.asList(request.getCateIdList().split(","));
            queryWrapper.lambda().in(PurchaseGoods::getGoodsCateId,cateIdList);
        }
        String status = request.getStatus();
        if(null != status){
            List<Integer> orderStatusList = new ArrayList<>();
            Integer orderStatus = null; //订单状态
            Integer refundStatus = null; //退款状态
            switch (status){
                case Constants.ORDER_STATUS_ALL:
                    orderStatusList = Stream.of(1,2,4,5,6,-1,-2).collect(Collectors.toList());
                    break;
                case Constants.ORDER_STATUS_NOT_SHIPPED: //未发货
                    orderStatus = 1;
                    break;
                case Constants.ORDER_STATUS_SPIKE: //待收货
                    orderStatus = 2;
                    break;
                case Constants.ORDER_STATUS_COMPLETE: //交易完成
                    orderStatus = 4;
                    break;
                case Constants.ORDER_STATUS_CANCEL: //取消
                    orderStatus = 5;
                    break;
                case Constants.ORDER_STATUS_REFUNDING: //退款中
                    refundStatus = 1;
                    break;
                case Constants.ORDER_STATUS_REFUNDED: //退货退款
                    orderStatus = -2;
                    break;
                case Constants.ORDER_STATUS_CONFIRM: //待确认
                    orderStatus = OrderStatusEnum.CONFIRM.getCode();
                    break;
                default:
                    orderStatus = -99;
                    break;
            }
            if(CollectionUtils.isNotEmpty(orderStatusList)){
                queryWrapper.lambda().in(PurchaseGoods::getStatus,orderStatusList);
            }
            if(orderStatus != null){
                queryWrapper.lambda().eq(PurchaseGoods::getStatus,orderStatus).ne(PurchaseGoods::getRefundStatus,1);
            }
            if(refundStatus != null){
                queryWrapper.lambda().eq(PurchaseGoods::getRefundStatus,refundStatus);
            }
        }
        //供应商/总后台采购单：新增商品筛选（商品名称/商品ID/国际编码）
        if (StringUtils.isNotBlank(request.getProductSearch())){
            queryWrapper.lambda().and(i -> i.like(PurchaseGoods::getGoodsId,request.getProductSearch())
                    .or().like(PurchaseGoods::getGoodsName,request.getProductSearch())
                    .or().like(PurchaseGoods::getGoodKeyword,request.getProductSearch()));
        }
        return queryWrapper;
    }


    private Integer getCount(StoreOrderSearchRequest request, String status) {
        StoreOrderSearchRequest searchRequest = new StoreOrderSearchRequest();
        BeanUtils.copyProperties(request, searchRequest);
        searchRequest.setStatus(status);
        QueryWrapper<PurchaseGoods> lambdaQueryWrapper = getStoreOrderListRequest(searchRequest);
        return this.count(lambdaQueryWrapper);
    }

}
